package com.guo.hui.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guo.hui.dao.shiro.TpRoleMapper;
import com.guo.hui.dao.shiro.TpUserRoleMapper;
import com.guo.hui.model.shiro.TpRole;
import com.guo.hui.model.shiro.TpUserRole;
import com.guo.hui.page.PageParam;
import com.guo.hui.service.RoleService;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Autowired
	private TpRoleMapper roleDao;
	@Autowired
	private TpUserRoleMapper userRoleDao;

	@Override
	public List<TpRole> selectByMap(Map<String, Object> map) {

		return roleDao.selectByMap(map);
	}

	@Override
	public void saveRole(TpRole tp) {
		tp.setCreateDate(new Date());
		tp.setModifyDate(new Date());
		roleDao.insert(tp);
	}

	@Override
	public void updateRole(TpRole tp) {
		tp.setModifyDate(new Date());
		roleDao.update(tp);
	}

	@Transactional
	@Override
	public void saveUserRole(Integer userid, Integer[] ids) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userid);
		List<TpUserRole> listUserRole = userRoleDao.selectByMap(map);
		if (listUserRole != null && listUserRole.size() > 0) {
			// 原本的角色ID集合
			List<Integer> oldRoids = new ArrayList<>();
			for (TpUserRole tp : listUserRole) {
				oldRoids.add(tp.getRoleId());
			}
			// 新选择的角色ID集合
			List<Integer> newRoids = Arrays.asList(ids);
			// 是否删除
			for (int i = 0, j = listUserRole.size(); i < j; i++) {
				if (!newRoids.contains(listUserRole.get(i).getRoleId())) {
					// 删除旧的数据 可使用批量操作
					userRoleDao.deleteById(listUserRole.get(i).getId());
				}
			}
			// 是否添加
			for (int m = 0, n = newRoids.size(); m < n; m++) {
				if (!oldRoids.contains(newRoids.get(m))) {
					userRoleDao.insert(getUserRole(userid, newRoids.get(m)));
				}
			}
		} else {
			for (Integer roleid : ids) {
				userRoleDao.insert(getUserRole(userid, roleid));
			}
		}
	}

	private TpUserRole getUserRole(Integer userid, Integer roleid) {
		TpUserRole tp = new TpUserRole();
		tp.setUserId(userid);
		tp.setRoleId(roleid);
		return tp;

	}

	@Override
	public PageInfo<TpRole> selectByMapPage(PageParam pageParm) {
		PageHelper.startPage(pageParm.getPage(), pageParm.getPageSize());
		List<TpRole> list = roleDao.selectByMap(pageParm.getSearchContent());
		return new PageInfo<TpRole>(list);
	}

}
